package main

import (
	"fmt"
	"log"
	"net/http"
)

func helloHandler(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/hello" {
		errStr := fmt.Sprintf("error path; current path: %s", r.URL.Path)
		http.Error(w, errStr, http.StatusNotFound)
		return
	}

	if r.Method != http.MethodGet {
		http.Error(w, "method not supported", http.StatusNotFound)
		return

	}

	fmt.Fprintf(w, "Hello!")

}

func formHandler(w http.ResponseWriter, r *http.Request) {
	// if r.URL.Path != "/form" {
	// 	http.Error(w, "error path", http.StatusNotFound)
	// 	return
	// }

	// if r.Method != http.MethodPost {
	// 	http.Error(w, "method not supported", http.StatusNotFound)
	// 	return
	// }

	if err := r.ParseForm(); err != nil {
		http.Error(w, "error parsing form", http.StatusBadRequest)
		return

	}

	name := r.FormValue("name")
	addr := r.FormValue("address")

	fmt.Fprintf(w, "Name: %s\n", name)
	fmt.Fprintf(w, "Address: %s\n", addr)

}

func main() {
	fileServer := http.FileServer(http.Dir("./static"))
	http.Handle("/", fileServer)
	http.HandleFunc("/form", formHandler)
	http.HandleFunc("/hello", helloHandler)

	fmt.Printf("Starting server at port 8080\n")

	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatal(err)
	}

}
